!function ($) {
    var MMPaginator = function (element, options) {
        this.$el = $(element);
        this.opts = options;
    };

    MMPaginator.prototype = {
        _initLayout: function () {
            var that = this;
            var $el = this.$el;
            var opts = this.opts;

            //用户偏好的缓存初始化
            var _key = window.location.href + 'mmPaginator';
            var storage = this.getLocalStorage();
            var $pSize = storage.getItem(_key);
            var $limit = 10;  //初始化limit
            if ($pSize) {
                $limit = $pSize;
            }
            $el.addClass("mmPaginator");
            var pgHtmls = [
                '<div class="totalCountLabel"></div>',
                '<ul class="pageList"></ul>',
                '<div class="limit"><select form="carform"></select></div>'
            ];
            $el.append($(pgHtmls.join('')));

            this.$totalCountLabel = $el.find('.totalCountLabel');
            this.$pageList = $el.find('.pageList');
            this.$limitList = $el.find('.limit select');

            var $limitList = this.$limitList
            $.each(opts.limitList, function () {
                var $option = $('<option></option>')
                    .prop('value', this)
                    .text(that.formatString(opts.limitLabel, [this]));
                $limitList.append($option);
            });
            $limitList.each(function () {

                // Cache the number of options
                var $this = $(this),
                    numberOfOptions = $(this).children('option').length;

                // Hides the select element
                $this.addClass('s-hidden');

                // Wrap the select element in a div
                $this.wrap('<div class="mmg-select disable"></div>');

                // Insert a styled div to sit over the top of the hidden select element
                $this.after('<div class="styledSelect"></div>');

                // Cache the styled div
                var $styledSelect = $this.next('div.styledSelect');

                // Show the user cache select option in the styled div
                $styledSelect.text($limit);
                $this.val($limit);

                // Insert an unordered list after the styled div and also cache the list
                var $list = $('<ul />', {
                    'class': 'mmg-options'
                }).insertAfter($styledSelect);

                // Insert a list item into the unordered list for each select option
                for (var i = 0; i < numberOfOptions; i++) {
                    $('<li />', {
                        text: $this.children('option').eq(i).text(),
                        rel: $this.children('option').eq(i).val()
                    }).appendTo($list);
                }

                // Cache the list items
                var $listItems = $list.children('li');

                // Show the unordered list when the styled div is clicked (also hides it if the div is clicked again)
                $styledSelect.click(function (e) {
                    if (!$('.mmg-select').hasClass('disable')) {
                        e.stopPropagation();
                        if($('div.styledSelect.active').length == 0){
                            $(this).toggleClass('active').next('ul.mmg-options').toggle();
                        }else{
                            $('div.styledSelect.active').each(function () {
                                $(this).removeClass('active').next('ul.mmg-options').hide();
                            });
                        }
                        autoIFrameHeight();
                    }
                });

                // Hides the unordered list when a list item is clicked and updates the styled div to show the selected list item
                // Updates the select element to have the value of the equivalent option
                $listItems.click(function (e) {
                    e.stopPropagation();
                    $styledSelect.text($(this).text()).removeClass('active');
                    $this.val($(this).attr('rel'));
                    $this.change();
                    $list.hide();
                    autoIFrameHeight();
                });

                // Hides the unordered list when clicking outside of it
                $(document).click(function () {
                    $styledSelect.removeClass('active');
                    $list.hide();
                    autoIFrameHeight();
                });

            });

            $limitList.on('change', function () {
                //使用方法存储limit缓存数据
                var pSize = $limitList.val();
                storage.setItem(_key, pSize);
                $el.data('page', 1);
                that.$mmGrid.load();
                $('.mmg-select').addClass('disable')
            });

        }

        , _plain: function (page, totalCount, limit) {
            var that = this;
            var $el = this.$el;
            var $pageList = this.$pageList;

            var totalPage = totalCount % limit === 0 ? parseInt(totalCount / limit) : parseInt(totalCount / limit) + 1;
            totalPage = totalPage ? totalPage : 0;
            if (totalPage === 0) {
                page = 1;
            } else if (page > totalPage) {
                page = totalPage;
            } else if (page < 1 && totalPage != 0) {
                page = 1;
            }
            //
            var $prev = $('<li class="prev"><a>上一页</a></li>');
            if (page <= 1) {
                $prev.addClass('disable');
            } else {
                $prev.find('a').on('click', function () {
                    $el.data('page', page - 1);
                    that.$mmGrid.load();
                });
            }
            $pageList.append($prev);
            /////
            var list = [1];
            if (page > 4) {
                list.push('...');
            }
            for (var i = 0; i < 5; i++) {
                var no = page - 2 + i;
                if (no > 1 && no <= totalPage - 1) {
                    list.push(no);
                }
            }
            if (page + 1 < totalPage - 1) {
                list.push('...');
            }
            if (totalPage > 1) {
                list.push(totalPage);
            }
            $.each(list, function (index, item) {
                var $li = $('<li><a></a></li>');
                if (item === '...') {
                    $li.addClass('').html('...');
                } else if (item === page) {
                    $li.addClass('active').find('a').text(item);
                } else {
                    $li.find('a').text(item).prop('title', '第' + item + '页').on('click', function (e) {
                        $el.data('page', item);
                        that.$mmGrid.load();
                    });
                }
                $pageList.append($li);
            });
            //
            var $next = $('<li class="next"><a title="下一页">下一页</a></li>');
            if (page >= totalPage) {
                $next.addClass('disable');
            } else {
                $next.find('a').on('click', function () {
                    $el.data('page', page + 1);
                    that.$mmGrid.load();
                });
            }
            $pageList.append($next);
        }

        , _search: function (page, totalCount, limit) {

        }

        , load: function (params) {
            var $el = this.$el;
            var $limitList = this.$limitList;
            var opts = this.opts;

            if (!params) {
                params = {};
            }

            var page = params[opts.pageParamName];
            if (page === undefined || page === null) {
                page = $el.data('page');
            }
            $el.data('page', page);

            var totalCount = params[opts.totalCountName];
            if (totalCount === undefined) {
                totalCount = 0;
            }
            $el.data('totalCount', totalCount);

            var limit = params[opts.limitParamName];
            if (!limit) {
                limit = $limitList.val();
            }
            this.$limitList.val(limit);

            this.$totalCountLabel.html(this.formatString(opts.totalCountLabel, [totalCount]));
            this.$pageList.empty();

            this._plain(page, totalCount, this.$limitList.val());
        }

        , formatString: function (text, args) {
            return text.replace(/{(\d+)}/g, function (match, number) {
                return typeof args[number] != 'undefined'
                    ? args[number]
                    : match
                    ;
            });
        }

        , params: function () {
            var opts = this.opts;
            var $el = this.$el;
            var $limitList = this.$limitList;

            var params = {};
            params[opts.pageParamName] = $el.data('page');
            params[opts.limitParamName] = $limitList.val();
            return params;
        }

        , init: function ($grid) {
            var that = this;
            var opts = that.opts;
            this.$mmGrid = $grid;
            this._initLayout();
            this.$mmGrid.on('loadSuccess', function (e, data) {
                $('.mmg-select').removeClass('disable');
                that.load(data);
            });

            var params = {};
            params[opts.totalCountName] = 0;
            params[opts.pageParamName] = opts.page;
            params[opts.limitParamName] = opts.limit;
            this.load(params);

            if ($grid.opts.indexCol) {
                var indexCol = $grid.opts.cols[0];
                indexCol.renderer = function (val, item, rowIndex) {
                    var params = that.params();
                    return '<label class="mmg-index">' +
                        (rowIndex + 1 + ((params[opts.pageParamName] - 1) * params[opts.limitParamName])) +
                        '</label>';
                };
            }

        }

        , getLocalStorage: function () {  //获取当前浏览器支持的缓存方法
            if (typeof localStorage == "object") {
                return localStorage;
            } else if (typeof globalStorage == "object") {
                return globalStorage[location.host];
            } else {
                console.warn("你的浏览器不支持高级存储")
            }
        }
    };

    $.fn.mmPaginator = function () {

        if (arguments.length === 0 || typeof arguments[0] === 'object') {
            var option = arguments[0]
                , data = this.data('mmPaginator')
                , options = $.extend(true, {}, $.fn.mmPaginator.defaults, option);
            if (!data) {
                data = new MMPaginator(this[0], options);
                this.data('mmPaginator', data);
            }
            return $.extend(true, this, data);
        }
        if (typeof arguments[0] === 'string') {
            var data = this.data('mmPaginator');
            var fn = data[arguments[0]];
            if (fn) {
                var args = Array.prototype.slice.call(arguments);
                return fn.apply(data, args.slice(1));
            }
        }
    };

    $.fn.mmPaginator.defaults = {
        style: 'plain'
        , totalCountName: 'total'        //totalCount
        , page: 1
        , pageParamName: 'pageNum'
        , limitParamName: 'pageSize'     //limit
        , limitLabel: '{0}'
        , pagHighlightColor: '#EE3A2B'
        , totalCountLabel: '共<span>{0}</span>条'
        , limitList: [10, 25, 50, 75, 100]
    };

    $.fn.mmPaginator.Constructor = MMPaginator;


}(window.jQuery);